import { 
  getSBPDay, getDBPDay, getChartDay, getDailyAvgPressure,
  getChartWeek, getChartMonth
} from '../../utils/api/BPLControl';
import { getHeartRate, getDailyAvgHeartRate, getNewestBPL, getLatestStepCount, getLatestBloodOxygen, getDailySleepSummary } from '../../utils/api/personalOverview';
import userBaseInfoState from '../../stores/userBaseInfo';
import { getPatientBaseObject } from '../../utils/api/patientBase';

Page({
  data: {
    // 概览区
    overview: {
      systolic: '--',
      diastolic: '--',
      heartRate: '--',
      riskLevel: '--',
      riskDesc: '--'
    },
    // 指标卡片区
    indicatorList: [
      { type: 'sleep', iconUrl: '/asserts/images/icon-sleep.png', title: '睡眠', value: '--', status: '睡眠正常' },
      { type: 'oxygen', iconUrl: '/asserts/images/icon-oxygen.png', title: '血氧饱和度', value: '--', status: '血氧正常' },
      { type: 'steps', iconUrl: '/asserts/images/icon-steps.png', title: '步数', value: '--', status: '步数正常' },
      { type: 'heartRate', iconUrl: '/asserts/images/icon-heart.png', title: '心率', value: '--', status: '心率正常' }
    ],
    medication: {
      date: '2024-05-21',
      list: [
        { time: '08:00', timeValue: '早上', name: '阿莫西林', dose: '2粒', taken: true },
        { time: '12:00', timeValue: '中午', name: '阿莫西林', dose: '2粒', taken: false },
        { time: '18:00', timeValue: '晚上', name: '阿莫西林', dose: '2粒', taken: false }
      ]
    },
    activeTab: 0,
    lastUpdateTime: 0,
    // 图表相关数据
    chartTimeType: 'week',
    chartDateRange: '09月13日-09月19日',
    currentDate: new Date(),
    chartData: {
      categories: ['今天'],
      series: [
        { name: '高压(收缩压)', data: [0], color: '#006EDB' },
        { name: '低压(舒张压)', data: [0], color: '#28C7C2' },
        { name: '心率', data: [0], color: '#FFCC00' }
      ]
    }
  },

  onLoad() {
    // 初始化日期范围
    this.updateDateRange();
    // 获取后端数据并初始化页面
    this.initPatientData();
  },

  onShow() {
    // 每次显示页面时刷新数据，但避免频繁请求
    const lastUpdateTime = this.data.lastUpdateTime || 0;
    const now = Date.now();
    // 如果距离上次更新超过30秒，才重新获取数据
    if (now - lastUpdateTime > 30000) {
      this.initPatientData();
      this.setData({ lastUpdateTime: now });
    }
  },

  // 获取用户信息并拉取数据
  initPatientData() {
    // 首先尝试从全局状态获取用户信息
    let userInfo = userBaseInfoState.data;
    
    if (userInfo && userInfo.patientUid) {
      // 如果全局状态中有用户信息，直接使用
      this.fetchOverviewData(userInfo.patientUid);
      this.fetchChartData(userInfo.patientUid);
      this.loadMedicationData();
    } else {
      // 如果没有，尝试通过openid获取用户信息
      const openid = wx.getStorageSync('openid');
      if (!openid) {
        wx.showToast({ title: '用户未登录', icon: 'none' });
        return;
      }
      
      // 获取用户基本信息
      const data = { wxUid: openid };
      getPatientBaseObject(data).then((res) => {
        console.log('获取用户信息成功', res);
        if (res.data && res.data.length > 0) {
          const userInfo = res.data[0];
          // 更新全局状态
          userBaseInfoState.onChangeData(userInfo);
          // 获取健康数据
          this.fetchOverviewData(userInfo.patientUid);
          this.fetchChartData(userInfo.patientUid);
          this.loadMedicationData();
          
        } else {
          wx.showToast({ title: '未找到用户信息', icon: 'none' });
        }
      }).catch((err) => {
        console.error("获取用户信息失败", err);
        wx.showToast({ title: '获取用户信息失败', icon: 'none' });
      });
    }
  },

  // 获取今日日期 yyyy-MM-dd 格式
  getTodayStr() {
    const today = new Date();
    const pad = v => (v < 10 ? '0' + v : v);
    return `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`;
  },

  // 拉取首页概览区数据
  fetchOverviewData(patientUid) {
    console.log('开始获取健康数据，patientUid:', patientUid);
    const date = this.getTodayStr();
    console.log('查询日期:', date);
    
    // 设置加载状态
    wx.showLoading({ title: '加载数据中...' });
    
    // 用于跟踪API调用完成情况
    let completedCalls = 0;
    const totalCalls = 5; // 最新血压(包含心率和风险)、步数、血氧、风险评估、睡眠
    
    const checkAllComplete = () => {
      completedCalls++;
      if (completedCalls >= totalCalls) {
        wx.hideLoading();
        console.log('所有健康数据加载完成');
        
        // 检查是否有数据，如果都是默认值则提示用户
        const currentData = this.data.overview;
        if (currentData.systolic === '--' && currentData.diastolic === '--' && currentData.heartRate === '--') {
          wx.showToast({
            title: '暂无健康数据，请先进行测量',
            icon: 'none',
            duration: 3000
          });
        }
      }
    };
    
    // 获取最新血压数据（收缩压和舒张压）
    getNewestBPL(patientUid).then(res => {
      console.log('最新血压数据:', res);
      if (res && res.code === 0 && res.data) {
        const systolic = res.data['收缩压'] ?? res.data.systolic ?? res.data['高压'] ?? '--';
        const diastolic = res.data['舒张压'] ?? res.data.diastolic ?? res.data['低压'] ?? '--';
        this.setData({ 
          'overview.systolic': systolic,
          'overview.diastolic': diastolic
        });
        console.log('血压设置成功 - 收缩压:', systolic, '舒张压:', diastolic);
      } else {
        console.log('血压数据为空或格式错误');
        this.setData({ 
          'overview.systolic': '--',
          'overview.diastolic': '--'
        });
      }
    }).catch((err) => {
      console.error('获取血压失败:', err);
      this.setData({ 
        'overview.systolic': '--',
        'overview.diastolic': '--'
      });
    }).finally(() => {
      checkAllComplete();
    });
    // 心率 - 使用最新心率数据
    getHeartRate(patientUid).then(res => {
      console.log('最新心率数据:', res);
      if (res && res.code === 0 && res.data) {
        const heartRate = res.data['心率'] ?? res.data.heartRate ?? '--';
        this.setData({ 
          'overview.heartRate': heartRate,
          'indicatorList[3].value': heartRate !== '--' ? heartRate + '次/分' : '--'
        });
        console.log('心率设置成功:', heartRate);
      } else {
        console.log('心率数据为空或格式错误');
        this.setData({ 'overview.heartRate': '--', 'indicatorList[3].value': '--' });
      }
    }).catch((err) => {
      console.error('获取心率失败:', err);
      this.setData({ 
        'overview.heartRate': '--', 
        'indicatorList[3].value': '--'
      });
    }).finally(() => {
      checkAllComplete();
    });
    // 风险评估
    getNewestBPL(patientUid).then(res => {
      console.log('风险评估数据:', res);
      if (res && res.code === 0 && res.data) {
        const riskLevel = res.data['风险评估'] ?? '--';
        const riskDesc = res.data['风险描述'] ?? '--';
        this.setData({
          'overview.riskLevel': riskLevel,
          'overview.riskDesc': riskDesc
        });
        console.log('风险评估设置成功:', riskLevel, riskDesc);
      } else {
        console.log('风险评估数据为空或格式错误');
        this.setData({ 'overview.riskLevel': '--', 'overview.riskDesc': '--' });
      }
    }).catch((err) => {
      console.error('获取风险评估失败 - 可能是数据库中没有血压记录:', err);
      // 设置默认值，不显示错误提示
      this.setData({ 
        'overview.riskLevel': '--', 
        'overview.riskDesc': '暂无数据' 
      });
    }).finally(() => {
      checkAllComplete();
    });

    // 最新步数
    getLatestStepCount(patientUid).then(res => {
      console.log('步数数据 - 完整:', res);
      // 后端直接返回数据对象，不是包装在{code, data}中
      if (res && res.steps !== undefined) {
        const steps = res.steps;
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'steps');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: `${steps}步` };
          this.setData({ indicatorList: list });
          console.log('步数设置成功:', steps);
        }
      } else if (res && res.code === 0 && res.data && res.data.steps !== undefined) {
        // 如果是标准响应格式
        const steps = res.data.steps;
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'steps');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: `${steps}步` };
          this.setData({ indicatorList: list });
          console.log('步数设置成功:', steps);
        }
      } else {
        console.log('步数数据为空');
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'steps');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: '--' };
          this.setData({ indicatorList: list });
        }
      }
    }).catch(err => {
      console.error('获取步数失败:', err);
      const list = [...this.data.indicatorList];
      const idx = list.findIndex(i => i.type === 'steps');
      if (idx !== -1) {
        list[idx] = { ...list[idx], value: '--' };
        this.setData({ indicatorList: list });
      }
    }).finally(() => {
      checkAllComplete();
    });

    // 最新血氧饱和度
    getLatestBloodOxygen(patientUid).then(res => {
      console.log('血氧数据 - 完整:', res);
      // 后端直接返回数据对象，不是包装在{code, data}中
      if (res && res.spo2 !== undefined) {
        const spo2 = res.spo2;
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'oxygen');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: `${spo2}%` };
          this.setData({ indicatorList: list });
          console.log('血氧设置成功:', spo2);
        }
      } else if (res && res.code === 0 && res.data && res.data.spo2 !== undefined) {
        // 如果是标准响应格式
        const spo2 = res.data.spo2;
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'oxygen');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: `${spo2}%` };
          this.setData({ indicatorList: list });
          console.log('血氧设置成功:', spo2);
        }
      } else {
        console.log('血氧数据为空');
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'oxygen');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: '--' };
          this.setData({ indicatorList: list });
        }
      }
    }).catch(err => {
      console.error('获取血氧失败:', err);
      const list = [...this.data.indicatorList];
      const idx = list.findIndex(i => i.type === 'oxygen');
      if (idx !== -1) {
        list[idx] = { ...list[idx], value: '--' };
        this.setData({ indicatorList: list });
      }
    }).finally(() => {
      checkAllComplete();
    });

    // 睡眠数据
    getDailySleepSummary({ patientUid, date }).then(res => {
      console.log('睡眠数据 - 完整:', res);
      if (res && res.code === 0 && res.data) {
        const sleepHours = res.data.sleepHours || 0;
        const sleepMinutes = res.data.sleepMinutes || 0;
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'sleep');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: `${sleepHours}小时 ${sleepMinutes}分钟` };
          this.setData({ indicatorList: list });
          console.log('睡眠设置成功:', sleepHours, '小时', sleepMinutes, '分钟');
        }
      } else {
        console.log('睡眠数据为空');
        const list = [...this.data.indicatorList];
        const idx = list.findIndex(i => i.type === 'sleep');
        if (idx !== -1) {
          list[idx] = { ...list[idx], value: '--' };
          this.setData({ indicatorList: list });
        }
      }
    }).catch(err => {
      console.error('获取睡眠失败:', err);
      const list = [...this.data.indicatorList];
      const idx = list.findIndex(i => i.type === 'sleep');
      if (idx !== -1) {
        list[idx] = { ...list[idx], value: '--' };
        this.setData({ indicatorList: list });
      }
    }).finally(() => {
      checkAllComplete();
    });
  },

  // 更新图表的横坐标、数据（如需多天数据可在此扩展）
  fetchChartData(patientUid) {
    const today = this.getTodayStr();
    this.setData({ 'chartData.categories': [today] });
    // 收缩压、舒张压、心率已在 fetchOverviewData 里同步到 chartData.series
  },

  // 加载用药数据
  loadMedicationData() {
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
    
    const mockData = [
      { time: '08:00', timeValue: '早上', name: '阿莫西林', dose: '2粒', taken: true },
      { time: '12:00', timeValue: '中午', name: '阿莫西林', dose: '2粒', taken: false },
      { time: '18:00', timeValue: '晚上', name: '阿莫西林', dose: '2粒', taken: false }
    ];

    this.setData({
      'medication.date': '2024-05-21',
      'medication.list': mockData
    });
  },

  onTabChange(e) {
    this.setData({ activeTab: e.detail.index });
    if (e.detail.index === 1) {
      // 切换到图表tab时，初始化图表并加载数据
      setTimeout(() => {
        const chartComponent = this.selectComponent('#bpChart');
        if (chartComponent) {
          chartComponent.initChart();
        }
        this.updateChartData();
      }, 100);
    }
  },

  // 处理标签页标题点击
  onTabClick(e) {
    const index = e.detail.index;
    const name = e.detail.name;
    const title = e.detail.title;
    
    console.log('标签页点击:', { index, name, title });
    
    // 如果点击的是"血压心率记录曲线"标签
    if (index === 1 || title === '血压心率记录曲线') {
      wx.navigateTo({
        url: '/pages/home/PressureRecord/index'
      });
    }
  },

  // 处理健康指标卡片点击
  handleCardClick(e) {
    const { type } = e.detail;
    console.log('[home] card click:', type);
    this.navigateToDetail({ currentTarget: { dataset: { type } } });
  },

  // 处理时间类型切换
  handleTimeChange(e) {
    const { type } = e.detail;
    this.setData({ chartTimeType: type });
    this.updateDateRange();
    this.updateChartData();
  },

  // 上一个时间段
  onPrevDate() {
    const { chartTimeType } = this.data;
    let { currentDate } = this.data;
    
    // 确保currentDate是有效的Date对象
    if (!(currentDate instanceof Date) || isNaN(currentDate.getTime())) {
      currentDate = new Date();
    }
    
    const newDate = new Date(currentDate.getTime());
    
    if (chartTimeType === 'day') {
      newDate.setDate(newDate.getDate() - 1);
    } else if (chartTimeType === 'week') {
      newDate.setDate(newDate.getDate() - 7);
    } else if (chartTimeType === 'month') {
      newDate.setMonth(newDate.getMonth() - 1);
    }
    
    this.setData({ currentDate: newDate });
    this.updateDateRange();
    this.updateChartData();
  },

  // 下一个时间段
  onNextDate() {
    const { chartTimeType } = this.data;
    let { currentDate } = this.data;
    
    // 确保currentDate是有效的Date对象
    if (!(currentDate instanceof Date) || isNaN(currentDate.getTime())) {
      currentDate = new Date();
    }
    
    const newDate = new Date(currentDate.getTime());
    
    if (chartTimeType === 'day') {
      newDate.setDate(newDate.getDate() + 1);
    } else if (chartTimeType === 'week') {
      newDate.setDate(newDate.getDate() + 7);
    } else if (chartTimeType === 'month') {
      newDate.setMonth(newDate.getMonth() + 1);
    }
    
    this.setData({ currentDate: newDate });
    this.updateDateRange();
    this.updateChartData();
  },

  // 更新日期范围显示
  updateDateRange() {
    const { chartTimeType } = this.data;
    let { currentDate } = this.data;
    
    // 确保currentDate是有效的Date对象
    if (!(currentDate instanceof Date) || isNaN(currentDate.getTime())) {
      currentDate = new Date();
      this.setData({ currentDate });
    }
    
    let dateRange = '';
    
    if (chartTimeType === 'day') {
      const month = currentDate.getMonth() + 1;
      const day = currentDate.getDate();
      dateRange = `${month}月${day}日`;
    } else if (chartTimeType === 'week') {
      const startDate = new Date(currentDate);
      const dayOfWeek = startDate.getDay();
      const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek; // 周一为起始
      startDate.setDate(startDate.getDate() + diff);
      
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + 6);
      
      const startMonth = startDate.getMonth() + 1;
      const startDay = startDate.getDate();
      const endMonth = endDate.getMonth() + 1;
      const endDay = endDate.getDate();
      
      dateRange = `${startMonth}月${startDay}日-${endMonth}月${endDay}日`;
    } else if (chartTimeType === 'month') {
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      dateRange = `${year}年${month}月`;
    }
    
    this.setData({ chartDateRange: dateRange });
  },

  // 更新图表数据
  updateChartData() {
    const { chartTimeType } = this.data;
    let { currentDate } = this.data;
    const userInfo = userBaseInfoState.data;
    const patientUid = userInfo?.patientUid;
    
    if (!patientUid) {
      console.error('用户信息不存在，无法更新图表');
      return;
    }
    
    console.log('更新图表数据，时间类型:', chartTimeType);
    
    // 确保currentDate是有效的Date对象
    if (!(currentDate instanceof Date) || isNaN(currentDate.getTime())) {
      console.log('currentDate无效，重置为当前日期');
      currentDate = new Date();
      this.setData({ currentDate });
    }
    
    console.log('当前日期:', currentDate, '格式化后:', this.formatDate(currentDate));
    
    // 显示加载状态
    wx.showLoading({ title: '加载图表数据...' });
    
    if (chartTimeType === 'day') {
      this.fetchDayChartData(patientUid, currentDate);
    } else if (chartTimeType === 'week') {
      this.fetchWeekChartData(patientUid, currentDate);
    } else if (chartTimeType === 'month') {
      this.fetchMonthChartData(patientUid, currentDate);
    }
  },

  // 获取日数据
  fetchDayChartData(patientUid, date) {
    const dateStr = this.formatDate(date);
    
    getChartDay({ patientUid, date: dateStr }).then(res => {
      console.log('日图表数据:', res);
      if (res && res.code === 0 && res.data) {
        this.processChartData(res.data, 'day');
      } else {
        this.setDefaultChartData('day');
      }
    }).catch(err => {
      console.error('获取日图表数据失败:', err);
      this.setDefaultChartData('day');
    }).finally(() => {
      wx.hideLoading();
    });
  },

  // 获取周数据
  fetchWeekChartData(patientUid, date) {
    const dateStr = this.formatDate(date);
    
    // 后端需要的参数名是 anyDateInWeek
    getChartWeek({ patientUid, anyDateInWeek: dateStr }).then(res => {
      console.log('周图表数据:', res);
      if (res && res.code === 0 && res.data) {
        this.processChartData(res.data, 'week');
      } else {
        this.setDefaultChartData('week');
      }
    }).catch(err => {
      console.error('获取周图表数据失败:', err);
      this.setDefaultChartData('week');
    }).finally(() => {
      wx.hideLoading();
    });
  },

  // 获取月数据
  fetchMonthChartData(patientUid, date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    
    // 后端需要的参数名是 year 和 month
    getChartMonth({ patientUid, year, month }).then(res => {
      console.log('月图表数据:', res);
      if (res && res.code === 0 && res.data) {
        this.processChartData(res.data, 'month');
      } else {
        this.setDefaultChartData('month');
      }
    }).catch(err => {
      console.error('获取月图表数据失败:', err);
      this.setDefaultChartData('month');
    }).finally(() => {
      wx.hideLoading();
    });
  },

  // 处理图表数据
  processChartData(data, timeType) {
    console.log('开始处理图表数据, timeType:', timeType, 'data:', data);
    let categories = [];
    let systolicData = [];
    let diastolicData = [];
    let heartRateData = [];
    
    if (Array.isArray(data) && data.length > 0) {
      data.forEach(item => {
        if (timeType === 'day') {
          categories.push(item.time || item.hour || item.recordTime || '--');
        } else if (timeType === 'week') {
          categories.push(item.date || item.day || item.dayOfWeek || '--');
        } else if (timeType === 'month') {
          categories.push(item.week || item.period || item.weekOfMonth || '--');
        }
        
        systolicData.push(item.systolic || item.avgSystolic || item.sbp || 0);
        diastolicData.push(item.diastolic || item.avgDiastolic || item.dbp || 0);
        heartRateData.push(item.heartRate || item.avgHeartRate || item.hr || 0);
      });
      
      console.log('图表数据处理完成:', {
        categories,
        systolicData,
        diastolicData,
        heartRateData
      });
    } else {
      console.warn('图表数据为空或格式错误，使用默认数据');
      this.setDefaultChartData(timeType);
      return;
    }
    
    // 更新数据
    this.setData({
      'chartData.categories': categories,
      'chartData.series[0].data': systolicData,
      'chartData.series[1].data': diastolicData,
      'chartData.series[2].data': heartRateData
    });
    
    // 更新图表显示
    setTimeout(() => {
      const chartComponent = this.selectComponent('#bpChart');
      if (chartComponent) {
        console.log('调用图表组件更新');
        chartComponent.updateChartOption();
      } else {
        console.error('找不到图表组件');
      }
    }, 100);
  },

  // 设置默认图表数据（当API返回空数据时）
  setDefaultChartData(timeType) {
    let categories = [];
    let systolicData = [];
    let diastolicData = [];
    let heartRateData = [];
    
    if (timeType === 'day') {
      categories = ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'];
      systolicData = [120, 118, 125, 130, 128, 122];
      diastolicData = [80, 78, 82, 85, 83, 81];
      heartRateData = [72, 70, 75, 80, 78, 74];
    } else if (timeType === 'week') {
      categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      systolicData = [125, 120, 128, 122, 130, 126, 124];
      diastolicData = [82, 80, 85, 81, 87, 83, 82];
      heartRateData = [75, 73, 78, 76, 80, 77, 75];
    } else if (timeType === 'month') {
      categories = ['第1周', '第2周', '第3周', '第4周'];
      systolicData = [124, 126, 122, 125];
      diastolicData = [82, 84, 80, 83];
      heartRateData = [76, 78, 74, 77];
    }
    
    // 更新数据
    this.setData({
      'chartData.categories': categories,
      'chartData.series[0].data': systolicData,
      'chartData.series[1].data': diastolicData,
      'chartData.series[2].data': heartRateData
    });
    
    // 更新图表显示
    const chartComponent = this.selectComponent('#bpChart');
    if (chartComponent) {
      chartComponent.updateChartOption();
    }
  },

  // 格式化日期为 yyyy-MM-dd 格式
  formatDate(date) {
    // 确保date是Date对象
    if (!(date instanceof Date)) {
      date = new Date(date);
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  navigateToDetail(e) {
    const type = e.currentTarget.dataset.type;
    const pages = {
      sleep: '/pages/health/sleep/index',
      oxygen: '/pages/health/oxygen/index',
      steps: '/pages/health/steps/index',
      heartRate: '/pages/health/heartRate/index'
    };
    const target = pages[type];
    if (!target) {
      console.warn('[home] navigateToDetail 未匹配到页面, type =', type);
      wx.showToast({ title: '页面未配置', icon: 'none' });
      return;
    }
    console.log('[home] navigate to:', target);
    wx.navigateTo({ url: target });
  }
});